package com.heimali.happyreader.db.dao;

import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.heimali.happyreader.db.DBHelper;
import com.heimali.happyreader.model.Article;
import com.heimali.happyreader.utils.SystemUtils;

public class ArticleDao extends BaseDao {
	public static final String TAG = "ArticleDao";

	public ArticleDao() {
		tableName = "article";
	}

	public int insert(Article item) {
		int count = 0;
		synchronized (DBHelper.writeLock) {
			SQLiteDatabase db = DBHelper.getDatabase();
			try {
				String sql = "insert into " + getTable() + " (articleID, sourceUrl, title, content) values (?, ?, ?, ?)";
				db.execSQL(sql, new Object[] { item.id, item.sourceUrl, item.title, item.content});
				count++;
			} catch (SQLException e) {
				e.printStackTrace();
				SystemUtils.Log(e.getMessage());
			}
		}
		return count;
	}

	public Article query(String articleID) {
		SQLiteDatabase db = DBHelper.getDatabase();
		Cursor cursor = null;
		Article article = null;
		try {
			String sql = "select articleID, sourceUrl, title, content from " + getTable() + " where articleID=? limit 1";
			cursor = db.rawQuery(sql, new String[] { articleID });
			while (cursor.moveToNext()) {
				article = new Article(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
			}
		} catch (SQLException e) {
			e.printStackTrace();
			SystemUtils.Log(e.getMessage());
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}
		return article;
	}
	
//	public void update() {
//	}
}
